package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.Resource;
import com.cfets.annualAssessment.mapper.ResourceMapper;
import com.cfets.annualAssessment.securityConfig.WebSecurityUserDetails;
import com.cfets.annualAssessment.service.ResourceService;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@ControllerAdvice
public class CurrentUserControllerAdvice {

    private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserControllerAdvice.class);

    LoadingCache<String,List<String> > cacheBuilder;

    public CurrentUserControllerAdvice(){
        cacheBuilder= CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .build(
                        new CacheLoader<String,List<String> >(){
                            @Override
                            public List<String> load(String role) throws Exception{

                                    //Todo 通过role获取resouce
                                    List<String> resource = Lists.newArrayList();
                                    List<Resource> resources = resourceService.findUrlIdByRole(role);
                                    for(Resource item:resources){
                                        resource.add(item.getUrl().toString());
                                    }
                                return resource;
                            }
                        }
                );
    }
    @Autowired
    private ResourceService resourceService;
    @ModelAttribute("currentUser")
    public User getCurrentUser(Authentication authentication) {
        return (authentication == null) ? null : (User) authentication.getPrincipal();
    }


    @ModelAttribute("resource")
    public Set<String> getResource(Authentication authentication){
        User user =(authentication == null) ? null : (User) authentication.getPrincipal();
        if(user==null){
            return null;
        }
        Iterator<GrantedAuthority> iterator = user.getAuthorities().iterator();
        Set<String> resourceList = Sets.newHashSet();
        while (iterator.hasNext()) {
            String role = iterator.next().getAuthority();
            List<String> resource = Lists.newArrayList();
            try {
                resourceList.addAll(cacheBuilder.get(role));
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
       return resourceList;
    }
//    @ModelAttribute("resource")
//    public Set<String> getResource(Authentication authentication){
//        User user =(authentication == null) ? null : (User) authentication.getPrincipal();
//        if(user==null){
//            return null;
//        }
//        Iterator<GrantedAuthority> iterator = user.getAuthorities().iterator();
//        GrantedAuthority grantedAuthority=null;
//        Set<String> resouseList = Sets.newHashSet();
//        while (iterator.hasNext()){
//            String role = iterator.next().getAuthority();
//            //Todo 通过role获取resouce
//            List<String> resource = Lists.newArrayList();
//            List<Resource> resources = resourceService.findUrlIdByRole(role);
//            for(Resource item:resources){
//                resource.add(item.getUrl().toString());
//            }
////            resource.add("/admin/attribute/index");
//            resouseList.addAll(resource);
//        }
//        return resouseList;
//    }

    @InitBinder
    private void dateBinder(WebDataBinder binder) {
        //The date format to parse or output your dates
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //Create a new CustomDateEditor
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        //Register it as custom editor for the Date type
        binder.registerCustomEditor(Date.class, editor);
    }


}
